// Package repository internal/repository/operation_log_repository.go
package repository

import (
	"gorm.io/gorm"
	"gozrd-admin-api/internal/entity/model"
)

// IOperationLogRepository 操作日志仓储接口
type IOperationLogRepository interface {
	CreateOperationLog(log model.SysOperationLog) error
	GetOperationLogList(pageNum, pageSize int, username, beginTime, endTime string) ([]model.SysOperationLog, int64, error)
	BatchDeleteOperationLog(ids []int) error
	DeleteOperationLogById(id int) error
	CleanOperationLog() error
}

// OperationLogRepository 操作日志仓储实现
type OperationLogRepository struct {
	db *gorm.DB
}

// NewOperationLogRepository 创建操作日志仓储
func NewOperationLogRepository(db *gorm.DB) IOperationLogRepository {
	return &OperationLogRepository{
		db: db,
	}
}

// CreateOperationLog 新增操作日志
func (r *OperationLogRepository) CreateOperationLog(log model.SysOperationLog) error {
	return r.db.Create(&log).Error
}

// GetOperationLogList 分页查询操作日志
func (r *OperationLogRepository) GetOperationLogList(pageNum, pageSize int, username, beginTime, endTime string) ([]model.SysOperationLog, int64, error) {
	var logs []model.SysOperationLog
	var count int64

	db := r.db.Model(&model.SysOperationLog{})

	// 添加查询条件
	if username != "" {
		db = db.Where("username = ?", username)
	}
	if beginTime != "" && endTime != "" {
		db = db.Where("create_time BETWEEN ? AND ?", beginTime, endTime)
	}

	// 获取总数
	err := db.Count(&count).Error
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).
		Order("create_time desc").
		Find(&logs).Error

	return logs, count, err
}

// BatchDeleteOperationLog 批量删除操作日志
func (r *OperationLogRepository) BatchDeleteOperationLog(ids []int) error {
	return r.db.Where("id in (?)", ids).Delete(&model.SysOperationLog{}).Error
}

// DeleteOperationLogById 删除单条操作日志
func (r *OperationLogRepository) DeleteOperationLogById(id int) error {
	return r.db.Delete(&model.SysOperationLog{}, id).Error
}

// CleanOperationLog 清空操作日志
func (r *OperationLogRepository) CleanOperationLog() error {
	return r.db.Exec("TRUNCATE TABLE sys_operation_log").Error
}
